﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using RGBFinder.Resources;
using Microsoft.Phone.Shell;
using System.Threading;


namespace RGBFinder
{
    public partial class ScorePage : PhoneApplicationPage
    {
        public ScorePage()
        {
            InitializeComponent();
        }

        public void EnableProgressBar()
        {
            ToggleProgressBar.IsEnabled = true;
            ToggleProgressBar.Visibility = System.Windows.Visibility.Visible;
            ToggleProgressBar.IsIndeterminate = true;
        }
        public void DisableProgressBar()
        {
            ToggleProgressBar.IsEnabled = false;
            ToggleProgressBar.Visibility = System.Windows.Visibility.Collapsed;
            ToggleProgressBar.IsIndeterminate = false;
        }
        string FixDateString(string s)
        {
            string s1 = s.Replace('/', '-').Replace(':', '-').Replace(' ', '_');
            return s1;
        }
        private void Submit_Button_Click(object sender, RoutedEventArgs e)
        {
            if (Name_Area.Text != "" && Name_Area.Text != Strings.WriteName)
            {
                Submit_Button.IsEnabled = false;
                Name_Area.IsEnabled = false;
                Focus();
                //http://fboscari.altervista.org/submit_RGBFinder_Score.php?name=francesco1&timer=00:10:10&tests=10
                //&score=1001&datetime=aaa&hash=aaa&difficult=Easy
                var query = "http://fboscari.altervista.org/submit_RGBFinder_Score.php?name=";
                query += Name_Area.Text;
                query += "&timer=";
                query += status.timer.ToString();
                query += "&tests=";
                query += status.tests;
                query += "&score=";
                query += Scoreboard.ComputeScore(status);
                query += "&datetime=";
                query += FixDateString(DateTime.Now.ToString());
                query += "&difficult=";
                query += status.difficulty.ToString();
                /*query += "&hash=";
                var s = Name_Area.Text + status.timer.ToString() + status.tests + Scoreboard.ComputeScore(status)+
                    FixDateString(DateTime.Now.ToString())+status.difficulty.ToString();
                var hash = Scoreboard.GetHashString(s);
                query += hash;
                query += Scoreboard.GetHashString(query);
                */
                new Thread(new ThreadStart(() =>
                {
                    Scoreboard.getHTML(query, GotHTML, ErrorGettingHTML);
                })).Start();

                Dispatcher.BeginInvoke(() => EnableProgressBar());

                Scoreboard.AddScore(new Score()
                {
                    name = Name_Area.Text,
                    score = Scoreboard.ComputeScore(status),
                    tests = status.tests,
                    time = status.timer.ToString()
                });
            }
        }

        void GotHTML(string html)
        {
            Dispatcher.BeginInvoke(() =>
            {
                DisableProgressBar();
                ResultsParser parser = new ResultsParser(html);
                var index = parser.GetPosition();
                index = "" + index;
                PhoneApplicationService.Current.State.Remove("RGBFinder_status");
                int result;
                if (int.TryParse(index, out result))
                {
                    MainPage.Global_Ranking = index;
                    MainPage.showScores = true;
                }

                NavigationService.GoBack();
            });

        }
        void ErrorGettingHTML()
        {
            Dispatcher.BeginInvoke(() =>
            {
                DisableProgressBar();
                if (MessageBox.Show(Strings.ProblemSendingScore, "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    Submit_Button_Click(null, null);
                }
                else
                {
                    Submit_Button.IsEnabled = true;
                    Name_Area.IsEnabled = true;
                }

            });
        }

        private void Name_Area_GotFocus(object sender, RoutedEventArgs e)
        {
            if (Name_Area.Text == Strings.WriteName)
                Name_Area.Text = "";
        }
        GameStatus status;
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            try
            {
                if (PhoneApplicationService.Current.State.ContainsKey("RGBFinder_status"))
                {
                    status = (GameStatus)PhoneApplicationService.Current.State["RGBFinder_status"];
                    PhoneApplicationService.Current.State.Remove("RGBFinder_status");

                    Timer_Area.Text = status.timer.ToString();
                    Tests_Area.Text = "" + status.tests;
                    switch (status.difficulty)
                    {
                        case GameDifficulty.Easy:
                            Difficulty_Area.Text = Strings.Easy;
                            break;
                        case GameDifficulty.Normal:
                            Difficulty_Area.Text = Strings.Normal;
                            break;
                        case GameDifficulty.Hard:
                            Difficulty_Area.Text = Strings.Hard;
                            break;
                        default:
                            Difficulty_Area.Text = "";
                            break;
                    }
                    Score_Area.Text = ""+Scoreboard.ComputeScore(status);
                }
                else
                {
                    status = null;
                    NavigationService.GoBack();
                }

            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }

        private void Name_Area_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                Submit_Button_Click(null, null);
        }

        

        
    }
}